<template>
  <div curPageName="edit213213124341111" style="height: 100%">
    <div class="product-card-part-form" v-show="modalTypeEdit == false">
      <div :class="modalTypeEdit == true ? 'content edit' : 'content'" v-loading="ck_loading">
        <!-- 表单内容 -->
        <!-- <span @click="get_postdata(specsArr)">提交的数据</span> -->
        <div class="modal_tit">
          <el-button
            @click="changeTypeEditFun()"
            v-if="modalTypeEdit == false"
            :icon="Edit"
            type="primary"
            link
            style="padding: 0; min-width: auto"
          >
            编辑
          </el-button>
        </div>

        <el-scrollbar>
          <el-table class="merak-table-container" :data="partsData" border style="width: 100%">
            <el-table-column prop="sku" :label='$t("goods_archive.sku_product")' />
            <el-table-column prop="category" :label='$t("goods_archive.category_bujian")'/>
            <el-table-column prop="color":label='$t("goods_archive.size_table_color")' />
            <el-table-column width="120" prop="part_quantity" :label='$t(" goods_archive.part_quantity")' />
            <el-table-column width="120" prop="split_sequence" :label='$t("goods_archive.split_sequence")' />
          </el-table>
        </el-scrollbar>
      </div>
      <div class="goods_spec_footer">
        <el-button @click="emits('close')">取消</el-button>
        <el-button type="primary">保存</el-button>
      </div>
    </div>

    <div class="product-card-part-form" v-show="modalTypeEdit == true">
      <div :class="modalTypeEdit == true ? 'content edit' : 'content'" v-loading="ck_loading">
        <div class="modal_tit">
          <div v-if="modalTypeEdit == true">
            <el-button @click="modalTypeEdit = false">{{ $t("merak.cancel") }}</el-button>
            <el-button @click="submitForm()" type="primary">{{ $t("merak.save") }}</el-button>
          </div>
        </div>

        <editTableMini
          v-bind="editMiniData"
          @plusCol="plusCol(editMiniData.dataValue)"
          @delOne="index => delOne(index, editMiniData.dataValue)"
        >
          <!-- 尺码插槽 -->
          <template #sku="{ scoped }">
            <div>
              <el-select
                @change="changesku(scoped.row.product_id, scoped.row)"
                filterable
                @visible-change="value => appenoptionsFun(value, scoped.row)"
                :validate-event="false"
                class="qf_select"
                placeholder="请选择"
                v-model="scoped.row.product_id"
              >
                <el-option  v-if="!scoped.row?.skuOptions?.length" :value="scoped.row.product_id" :label="scoped.row.sku" />
                <template v-else>
                  <el-option :label="item.label" :value="item.value" v-for="item in scoped.row.skuOptions" :key="item" />
                </template>
              </el-select>
            </div>
          </template>
          <template #category="{ scoped }">
            <div>
              {{ scoped.row.category }}
            </div>
          </template>
          <template #color="{ scoped }">
            <div>
              {{ scoped.row.color }}
            </div>
          </template>

          <template #part_quantity="{ scoped }">
            <div>
              <el-input v-number :validate-event="false" class="editCon" v-model="scoped.row.part_quantity"></el-input>
              <span class="errorTip" v-if="scoped.row.part_quantity_errInfo">{{ scoped.row.part_quantity_errInfo }}</span>
            </div>
          </template>
          <template #split_sequence="{ scoped }">
            <div>
              <el-input v-number :validate-event="false" class="editCon" v-model="scoped.row.split_sequence"></el-input>
              <span class="errorTip" v-if="scoped.row.split_sequence_errInfo">{{ scoped.row.split_sequence_errInfo }}</span>
            </div>
          </template>
        </editTableMini>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Plus, Edit, Delete, EditPen, CaretTop, CaretBottom } from "@element-plus/icons-vue";

import { ref, reactive, onMounted, getCurrentInstance, nextTick, watch, computed, inject } from "vue";
import MerakControl, { MerakControlProps } from "@/components/MerakControl";

import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";

import { ElButton, ElScrollbar, ElForm, ElMessage, ClickOutside as vClickOutside } from "element-plus";
import I18n from "@/languages/index";
import basicTableSum from "@/components/MerakEditTable/components/basicTable/moreEdit.vue";

import { ResultEnum } from "@/enums/httpEnum";
import { getParts, getPartsInfo, saveParts } from "@/api/modules/goodsArchive/addGoodsArchive";
import { useRouter, useRoute } from "vue-router";
import editTableMini from "@/components/MerakEditTable/components/editTableMini/index.vue";
import uploadPic from "@/components/uploadFileMerak/picUpload.vue";
import { number } from "mathjs";
import { BlockKeys, BlockRefs } from "../index";
const $t = I18n.global.t;
const { query } = useRoute();
const product_id_zz = ref("111");
const selectzz = [{ label: "zhejzhen", value: "111" }];

const props = defineProps<{
  // 当前模式 default: 添加  edit: 编辑  copy: 复制
  type: FormType;
  //单条数据
  row?: Record<string, any>;
  // 表单配置项
  formConfig: Record<string, any>;
  // 表单渲染数据
  specsInitial: Record<string, any>;
  // 表单只读字段集合
  formReadonly: Array<string>;
  // 回显数据
  formValue: Array<Record<string, any>>;
}>();

const emits = defineEmits<{
  close: [saved?: boolean];
}>();

//部件信息展示
const partsData = ref([]);
const ck_loading = ref(false);
const editMiniData = ref({
  columnsValue: [
    { field: "sku", title: $t("goods_archive.sku_product") },
    { field: "category", title: $t("goods_archive.category_bujian")},
    { field: "color", title:$t("goods_archive.size_table_color") },
    { field: "part_quantity", title:$t(" goods_archive.part_quantity") },
    { field: "split_sequence", title: $t("goods_archive.split_sequence") }
  ],
  dataValue: [
    {
      sku: "",
      category: "",
      color: "",
      part_quantity: "",
      split_sequence: ""
    }
  ]
});
const skuOptions = ref([]);
const modalTypeEdit = ref(false);
const skuinfo = ref([]);

// 初始化选项
onMounted(() => {
  console.log(props.row.product_id);
  getPartsInfoFun();
  getPartsFun();
});

const changeTypeEditFun = row => {
  modalTypeEdit.value = true;
};

const changesku = (product_id, row) => {
  var new_skuinfo = JSON.parse(JSON.stringify(skuinfo.value));
  new_skuinfo.filter(item => {
    if (item.product_id == product_id) {
      console.log(item);
      row.category = item.category;
      row.color = item.color;
    }
  });
};

// 操作小表格的增加
const plusCol = data => {
  var _obj = {
    product_id: "",
    sku: "",
    category: "",
    color: "",
    part_quantity: "",
    split_sequence: "",
    skuOptions: skuOptions.value
  };
  data.push(_obj);
};
// 操作小表格的删除
const delOne = (index, ever, type, everdata) => {
  if (ever.length > 1) {
    ever.splice(index, 1);
  }
};

const appenoptionsFun = (kye, row) => {
  console.log(row);
  if (kye) {
    row.skuOptions = skuOptions.value;
  }
};

const submitForm = () => {
  console.log(editMiniData.value.dataValue);

  for (let index = 0; index < editMiniData.value.dataValue.length; index++) {
    const element = editMiniData.value.dataValue[index];
    console.log(element);
    element.part_quantity_errInfo = "";
    element.split_sequence_errInfo = "";
    element.evergo = 1;
    if (element.product_id) {
      if (element.part_quantity == "") {
        element.part_quantity_errInfo = "不能为空";
        element.evergo = 0;
      }
      if (element.split_sequence == "") {
        element.split_sequence_errInfo = "不能为空";
        element.evergo = 0;
      }
    }
  }

 

  const post_editMiniData = JSON.parse(JSON.stringify(editMiniData.value.dataValue));
  console.log()
  var go=1;
  post_editMiniData.forEach(element => {
    if(element.evergo==0){
      go=0;
    }
  });
  
  if(go==0){
    return false;

  }
  const savedata = post_editMiniData.filter(item => {
    if (item.evergo == 1 && item.product_id) {
      item["product_id"] = item.product_id;
      skuOptions.value.filter(op => {
        if (op.value == item.product_id) {
          item["sku"] = op.label;
        }
      });
      delete item.evergo;
      delete item.skuOptions;

      return item;
    }
  });
  console.log(savedata);

  var godata = {
    product_id: props.row.product_id,
    inn: savedata
  };

  savePartsFun(props.row.product_id, godata);
};

const savePartsFun = (product_id, data) => {
  ck_loading.value = true;
  saveParts(data).then(({ code, data }) => {
    ck_loading.value = false;
    if (code == ResultEnum.SUCCESS) {
      ElMessage.success("修改部件信息成功");
      getPartsInfoFun(product_id);
      modalTypeEdit.value = false;
    } else {
    }
  });
};

const getPartsInfoFun = product_id => {
  ck_loading.value = true;
  var product_id = props.row.product_id;
  getPartsInfo(product_id).then(({ code, data }) => {
    ck_loading.value = false;
    if (code == ResultEnum.SUCCESS) {
      partsData.value = data;
      editMiniData.value.dataValue = JSON.parse(JSON.stringify(data));
      if (data.length < 1) {
        plusCol(editMiniData.value.dataValue);
      }
    } else {
    }
  });
};

const getPartsFun = product_id => {
  var product_id = props.row.product_id;
  getParts(product_id).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      console.log(data);
      var skuOptions_temp = [];
      skuinfo.value = data;
      for (let index = 0; index < data.length; index++) {
        var sku_ever = {};
        const element = data[index];
        sku_ever["label"] = element.sku;
        sku_ever["value"] = element.product_id;
        skuOptions_temp.push(sku_ever);
      }
      skuOptions.value = skuOptions_temp;
      console.log(skuOptions.value);
    } else {
    }
  });
};
</script>

<style scoped lang="scss">
.content {
  display: flex;
  flex-direction: column;
}
.content.edit {
  margin-bottom: 0;
  display: block;
}
.product-card-part-form {
  display: flex;
  flex-direction: column;
  height: 100%;
  & > :first-child {
    flex: 1;
    margin-bottom: var(--merak-padding);
    min-height: 0;
  }
  & > :first-child.edit {
    flex: auto;
  }
  .errorTip {
    font-size: 11px;
    color: rgb(228, 15, 15);
    text-align: left;
  }
  .handler {
    text-align: right;
  }
  .goods_spec_footer {
    border-top: 1px solid var(--el-border-color-lighter);
    padding: var(--el-drawer-padding-primary);
    padding-bottom: 0;
    margin: 0 -30px;
    text-align: center;
    background-color: #fff;
    z-index: 9;
  }
  .modal_tit {
    margin-bottom: 10px;
    text-align: right;
  }
}
</style>
